import webapp2
import datetime,random,json
from google.appengine.ext import db
from google.appengine.datastore.datastore_v4_pb import GqlQuery
from google.appengine.ext.ndb.tasklets import sleep

class dal_select(webapp2.RequestHandler):
    def get(self):
        crowdsum = CrowdSum.get_by_key_name(key_names="mnm")
        if self.request.get("average"):
            if (crowdsum):
                average=crowdsum.sum/crowdsum.count
                self.response.write(str(average))
        if self.request.get("middle"):             
            
            if (crowdsum.count%2 == 0):
                # if even number, get 2 object in the middle
                middleindex=crowdsum.count/2-1 
                limit=2
            else:
                # if off number, get only the middle
                middleindex=crowdsum.count/2
                limit=1
            query = Result.all()
            query.order("-answer")
            middleObj=query.fetch(limit=limit,offset=middleindex)
            sum=0
            for x in middleObj:
                sum+=x.answer
                
            # if limit is 2 (even), middle is the average of the 2 in the middle
            # if limit is 1 (odd),  middle object is selected
            middle=sum/limit

            self.response.write(str(middle))
        if self.request.get("topten"):
            query = Result.all()
            query.order("distance")
            topten = query.fetch(limit=10)
            self.response.headers['Content-Type'] = 'application/json'   
           
            topDict={"topten":[]}
            for answer in topten:
                jsonObj={ "name" : answer.name, "answer" : answer.answer, "distance" : answer.distance }
                topDict.get("topten").append(jsonObj)
            self.response.write(json.dumps(topDict))
                
class dal_insert(webapp2.RequestHandler):
    # correctAnswers holds a dict of the real answers
    correctanswer = 100
    
    def get(self):
        if self.request.get("subscribe"):
            email = self.request.get("email")
            subscriber = Subscriber(email=email)
            subscriber.put()
        if self.request.get("filldb") and self.request.get("password") == "secretPass":
            for i in range(100):
                for game in ["pie","wheel","beer"]:
                    result=random.randint(1,1000)
                    resultObj = Result(game=game,result=result,distance=abs(result-self.correctAnswers.get(game)))
                    resultObj.put()
                    crowdsum = CrowdSum.get_or_insert(key_name=game,correctanswer=self.correctAnswers.get(game))
                    crowdsum.sum += result
                    crowdsum.count += 1
                    crowdsum.put()
            
    def post(self):
        # TODO: change to post requests
        if self.request.get("new_session"):
            # create Session object with date, and return it's id in the response
            session = Session(logontime=datetime.datetime.now())
            session.put()
            self.response.write(session.key().id())
            
        elif self.request.get("click"):
            # create Click object with date, source id, and set a session as parent 
            source=self.request.get("source")
            user_id=self.request.get("id")
            session_k = Session.get_by_id(ids=int(user_id)) 
            click = Click(clicktime=datetime.datetime.now() , source=source , parent=session_k)
            click.put()
            
        elif self.request.get("subscribe"):
            email = self.request.get("email")
            subscriber = Subscriber(email=email)
            subscriber.put()
            
        elif self.request.get("submit"):
            answer = int(self.request.get("answer"))
            name = self.request.get("name")

            # put into result object
            resultObj = Result(answer=answer,name=name,distance=abs(answer-self.correctanswer))
            resultObj.put()
            # and put into CrowdSum object
            crowdsum = CrowdSum.get_or_insert(key_name="mnm",correctanswer=self.correctanswer)
            crowdsum.sum += answer
            crowdsum.count += 1
            crowdsum.put()

class CrowdSum(db.Model):
    correctanswer = db.IntegerProperty(required=True)
    sum = db.IntegerProperty(default=0,required=True)
    count = db.IntegerProperty(default=0,required=True)

class Result(db.Model):
    answer= db.IntegerProperty(required=True)
    name= db.StringProperty(required=True)
    distance = db.IntegerProperty(required=True)
            
class Session(db.Model):
    logontime = db.DateTimeProperty(required=True)
    name = db.StringProperty()
  
class Click(db.Model):
    clicktime = db.DateTimeProperty(required=True)
    source = db.StringProperty()

class Subscriber(db.Model):
    email = db.StringProperty(required=True)
    
application = webapp2.WSGIApplication([
    ('/db_select', dal_select),
    ('/db_insert', dal_insert)
], debug=True)
